﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Collections.Generic;
using CeA.Reports.Atendimento.DataAccess.DTO;
using Qtech.Reports.Atendimento.Services;
using CeA.Reports.Atendimento.DataAccess.Criteria;
using CeA.Reports.Atendimento.Web.Helpers;
using System.Threading;
using System.Globalization;

namespace CeA.Reports.Atendimento.Web.site {
    public partial class relatorioplanejadoexecutado : System.Web.UI.Page {
        
        protected void Page_Init(object sender, EventArgs e)                {
            cmdVoltar.Click += new EventHandler(cmdVoltar_Click);
            cmdSearch.Click +=new EventHandler(cmdSearch_Click);
            cmdExportarExcel.Click += new EventHandler(cmdExportarExcel_Click);
        }

        
        protected void Page_Load(object sender, EventArgs e)                {
            if (PreviousPage != null) {
                this.CodigoLoja = PreviousPage.CodigoLoja;
                this.PageMode = PreviousPage.PageMode;
            }

            if (Request.QueryString["loja"] != null) {
                this.CodigoLoja = Convert.ToInt32(Request.QueryString["loja"]);
                this.PageMode = "PLANEJAMENTO_EXECUTADO";
            }

            if (this.CodigoLoja == 0)
                Server.Transfer("/admin/loja.aspx?tag=planexec");

            if (!Page.IsPostBack)
                carregar();

        }


        protected void cmdVoltar_Click(object sender, EventArgs e)          {
            NavigationHelper.RefererRedirect("/admin/loja.aspx?tag=planexec");
        }


        protected void cmdSearch_Click(object sender, EventArgs e)          {
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pt-BR");
            try {
                int ano = Convert.ToDateTime(txtData.Text).Year;
                int mes = Convert.ToDateTime(txtData.Text).Month;
                int dia = Convert.ToDateTime(txtData.Text).Day;
                carregarTabela(ano, mes, dia);

                cmdExportarExcel.Visible = true;//e.ExportaRelatorio;
                pnlImprimir.Visible = true;
                report.Visible = true;

            }
            catch(FormatException) {
                MessageBox.pop("Formato de data inválido. Utilize o formato dd/mm/aaaa.");
            }
        }


        protected void cmdExportarExcel_Click(object sender, EventArgs e)   {
            //limpo a resposta do HTTP
            Response.Clear();

            //adiciono o cabeçalho que faz o .Net entender que se trata de um xls
            Response.AddHeader("content-disposition", "attachment;filename=planejamentoexecutado_report.xls");

            //zero o charset
            Response.Charset = "";

            //desabilito o cache do browser
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            //Seto o content type para xls
            Response.ContentType = "application/vnd.xls";

            //Crio um String Writer
            System.IO.StringWriter sWr = new System.IO.StringWriter();

            //Transformo em HTML String Writer
            System.Web.UI.HtmlTextWriter hWr = new HtmlTextWriter(sWr);

            //Mando o datagrid (que deve ser criado antes de renderizar o HtmlTextWriter criado...
            cmdSearch_Click(sender, e);
            report.RenderControl(hWr);

            //mando escrever na tela. Com todos os cabeçalhos setados, é aberto para salvar o XML
            Response.Write(sWr.ToString());

            //Fecho a resposta.
            Response.End();
        }


        private void carregar()                                             {
            int lojaId = this.CodigoLoja;
            if (lojaId > 0) {
                LojaDTO ds = CadastroFacade.GetLoja(lojaId);
                txtSigla.Text = ds.Sigla;
                txtNome.Text = ds.Nome;
            }
        }


        private void carregarTabela(int ano, int mes, int dia)              {
            List<PlanejamentoDTO> planRows = CadastroFacade.FindPlanejamento(new PlanejamentoCriteria() {
                Ano = ano,
                Mes = mes,
                Dia = dia,
                LojaId = this.CodigoLoja
            });

            
            HtmlTable table = new HtmlTable();
            table.Border = 0;
            table.CellSpacing = 1;
            table.CellPadding = 1;
            table.Style.Add("table-layout", "auto");
            table.ID = "table_report";



            if (planRows.Count == 0) {
                table.Width = "100%";
                table.Rows.Add(new HtmlTableRow() { Height = "18px" });
                table.Rows.Add(new HtmlTableRow() { Height = "18px" });

                table.Rows[0].Attributes.Add("class", "th");
                table.Rows[0].Cells.Add(new HtmlTableCell());
                //table.Rows[0].Cells.Add(new HtmlTableCell());
                table.Rows[0].Cells[0].Controls.Add(new Label() { Text = "Nenhum registro encontrado." });

                report.Controls.Add(table);
                return;
            }


            table.Rows.Add(new HtmlTableRow() { Height = "18px", BgColor = "silver"});
            table.Rows.Add(new HtmlTableRow() { Height = "18px" });
            table.Rows.Add(new HtmlTableRow() { Height = "18px" });
            table.Rows.Add(new HtmlTableRow() { Height = "18px" });
            table.Rows.Add(new HtmlTableRow() { Height = "18px" });
         
            table.Rows[1].Cells.Insert(0, new HtmlTableCell() { InnerHtml = "<span style='display:block;width:120px'><b>Planejamento</b></span>"});
            table.Rows[2].Cells.Insert(0, new HtmlTableCell() { InnerHtml = "<b>Executado</b>" });
            table.Rows[3].Cells.Insert(0, new HtmlTableCell() { InnerHtml = "<b>Diferença(#)</b>" });
            table.Rows[4].Cells.Insert(0, new HtmlTableCell() { InnerHtml = "<b>Diferença (%)</b>" });


            // Monta o Header da Tabela
            List<HoraDTO> horaRows = CadastroFacade.FindHora();
            foreach (HoraDTO hora in horaRows) {
                table.Rows[0].Cells.Add(new HtmlTableCell() { InnerHtml = "<span style='display:block; width:45px; text-align:center'>" +  hora.HoraString + "</span>" });
                table.Rows[1].Cells.Add(new HtmlTableCell() { InnerText = "P",Align = "center"});
                table.Rows[2].Cells.Add(new HtmlTableCell() { InnerText = "E",Align = "center" });
                table.Rows[3].Cells.Add(new HtmlTableCell() { InnerText = "#",Align = "center" });
                table.Rows[4].Cells.Add(new HtmlTableCell() { InnerText = "%",Align = "center" });
            }

            table.Rows[0].Cells.Insert(0, new HtmlTableCell("td") { InnerHtml = "&nbsp;" });
            
            table.Rows.Insert(0, new HtmlTableRow());
            //table.Rows[0].Cells.Add(new HtmlTableCell("td"));
            //table.Rows[0].Cells.Add(new HtmlTableCell("td") { ColSpan = horaRows.Count+1, InnerHtml = "<h2>Período de Pico</h2>" });
            
            //table.Rows[0].Attributes.Add("class", "th");
            table.Rows[1].Attributes.Add("class", "th");
            table.Rows[2].Attributes.Add("class", "cor-1");
            table.Rows[3].Attributes.Add("class", "cor-2");
            table.Rows[4].Attributes.Add("class", "cor-1");
            table.Rows[5].Attributes.Add("class", "cor-2");

            

            int idx = 1;

            foreach (PlanejamentoDTO plan in planRows) {
                table.Rows[2].Cells[idx].InnerText = plan.QtdeMesaPlanejada.ToString("N2");
                table.Rows[3].Cells[idx].InnerText = plan.QtdeMesaExecutada.ToString("N2");
                table.Rows[4].Cells[idx].InnerText = (plan.QtdeMesaPlanejada - plan.QtdeMesaExecutada).ToString("N2");
                try {
                    int difPercentual = Convert.ToInt32((plan.QtdeMesaExecutada * 100 / plan.QtdeMesaPlanejada) - 100);

                    if (difPercentual < 0)
                        table.Rows[5].Cells[idx].InnerHtml = "<span style='color:red'>" + difPercentual.ToString() + "%</span>";
                    else
                        table.Rows[5].Cells[idx].InnerHtml = "<span>" + difPercentual.ToString() + "%";
                }
                catch {
                    table.Rows[5].Cells[idx].InnerText = "n/a";
                }
                idx++;
            }

            report.Controls.Add(table);
        }


        #region -- Page Properties --------------------------------------------

        public int CodigoLoja   {
            get {
                if (ViewState["m_codigoLoja"] != null)
                    return Convert.ToInt32(ViewState["m_codigoLoja"]);
                return 0;
            }
            set {
                ViewState.Add("m_codigoLoja", value);
            }
        }

        public string PageMode  {
            get {
                if (ViewState["m_pageMode"] != null)
                    return Convert.ToString(ViewState["m_pageMode"]);
                return "PLANEJADO_EXECUTADO";
            }
            set {
                ViewState.Add("m_pageMode", value);
            }
        }

        #endregion
    }
}
